<?php

namespace app\home\controller;

use app\common\model\Post as P;
use app\common\model\User as U;
use think\facade\Db;
use app\common\validate\User as UserValidate;
use think\facade\App;
class Index extends Base
{
    public function index()
    {
        //置顶文章
        $configTopArticle = Db::name("system")->where("config","topArticle")->value("value");
        $topArticle = P::withJoin(['userInfo'	=>	['username','uid'],'cate' =>['cate_name']])->where("id","in",$configTopArticle)->limit(4)->select();

        //轮播图文章
        $carouselConfig = Db::name("system")->where("config","carousel")->value("value");
        $carouselArticle = Db::name("post")->field("id,title,cover_image")->where("id","in", $carouselConfig)->select();
        return view('/index',[
            'topArticle'=>$topArticle,
            'carousel' => $carouselArticle,
        ]);
    }

    public function login()
    {
        if(request()->isAjax()){
            $data = input("post.");
            if (session("loginCount") === null){
                session("loginCount",1);
            }else{
                session("loginCount",session("loginCount") + 1);
            }

            $UserValidate = new UserValidate();
            if(!$UserValidate->scene("login")->check($data)){
                return ["code" =>0,"count" => session("loginCount"),"msg" => $UserValidate->getError()];
            }

            if (session("loginCount") > 5){
                if(!captcha_check($data["code"])){
                    return ["code" =>0,"count" => session("loginCount"), "msg" =>"验证码错误"];
                };

            }

            $where["email"] = $data["email"];
            $where["password"] = md5($data["password"]);
            $userInfo = U::where($where)->find();
            if ($userInfo){
                session("loginUid",$userInfo["uid"]);
                session("loginCount",null);
                return ["code" => 1,"msg" => "登录成功"];
            }
            return ["code" => 0,"count" => session("loginCount"), "msg" => "用户名或密码错误"];
        }else{
            return view("/login");
        }
    }
    public function register()
    {
        if(request()->isAjax()){
            $data = input("post.");
            $UserValidate = new UserValidate();
            if(!$UserValidate->scene("reg")->check($data)){
                return ["code" =>0,"msg" => $UserValidate->getError()];
            }
            if(Cache::get('regEmail') == $data['email'] && Cache::get('regCode') == $data['code'] ){
                $data1["password"] = md5($data["pwd"]);
                $data1["username"] = $data["email"];
                $data1["email"] = $data["email"];
                $data1["create_time"] = time();
                $userId = Db::name("user")->insertGetId($data1);
                $usergGroup = Db::name("auth_group_user")->insert(["uid" =>$userId ,"group_id" => 2]);
                if($userId && $usergGroup){
                    cache('regEmail', NULL);
                    cache('regCode', NULL);
                    return ["code" =>1,"msg" => "注册成功"];
                }
                return ["code" =>0,"msg" => "注册失败"];
            }else{
                return ["code" =>0,"msg" => "验证码错误"];
            }
        }else {
            return view("/register");
        }
    }
    //注册发送邮箱验证码
    public function regSendEmail()
    {
        $email = input("email");
        $checkmail="/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/";
        if(!preg_match($checkmail,$email)){
            return json(["code" => 0,"msg" => "电子邮箱格式错误"]);
        }
        $code = rand(10000,99999);
        $content = "欢迎注册TnCMS用户，您的注册验证码为:" .$code ."<br />(30分钟内有效)";
        $sendEmail = sendEmail($email,"账号激活",$content);
        if($sendEmail["code"] === 200){
            Cache::set('regEmail',$email,1800);
            Cache::set('regCode',$code,1800);
            return json(["code" =>1,"msg" => $sendEmail["msg"]]);
        }
        return json(["code" =>0,"msg" => $sendEmail["msg"]]);
    }

    //找回密码发送邮箱验证码
    public function pwdSendEmail()
    {
        $email = input("email");
        $checkmail="/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/";
        if(!preg_match($checkmail,$email)){
            return json(["code" => 0,"msg" => "电子邮箱格式错误"]);
        }
        $code = rand(10000,99999);
        $content = "找回TnCMS登录密码，您的验证码为:" .$code ."<br />(30分钟内有效)";
        $sendEmail = sendEmail($email,"【TnCMS】密码找回验证码",$content);
        if($sendEmail["code"] === 200){
            Cache::set('pwdEmail',$email,1800);
            Cache::set('pwdCode',$code,1800);
            return json(["code" =>1,"msg" => $sendEmail["msg"]]);
        }
        return json(["code" =>0,"msg" => $sendEmail["msg"]]);
    }
    //找回密码
    public function pwdRetrieve()
    {
        $email = input("email");
        $code = input("code");
 
        if(Cache::get('pwdEmail') ==  $email && Cache::get('pwdCode') == $code){
            $password = rand(100000,999999);
            $updatePwd = Db::name("user")->where("email",$email)->update(["password" =>md5($password)]);
            if($updatePwd){
                cache('pwdEmail', NULL);
                cache('pwdCode', NULL);
                $content = "您的新密码为：".$password ."，请牢记并及时更改";
                $sendEmail = sendEmail($email,"【TnCMS】密码重置",$content);
                return json(["code" => 1, "msg" => "新密码已发至您的邮箱，请查收。"]);
            }
            return json(["code" => 0, "msg" =>"系统错误"]);
        }
        return json(["code" => 0, "msg" =>"验证码错误"]);
    }
}